﻿namespace WMS6.SQLServerDAL
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;
    using System.Data.SqlClient;
    using WMS6.Common;
    using WMS6.DataEntity;
    using WMS6.DBUtility;
    using WMS6.IDAL;
    using WMS6.QueryEntity;

    public class AuditDataDA : IAuditDataDA
    {
        private string ACTION = "@ACTION";
        private string COL_NAME = "@COL_NAME";
        private string CREATED_BY = "@CREATED_BY";
        private string CREATED_DATE = "@CREATED_DATE";
        private string NEW_VALUE = "@NEW_VALUE";
        private string OLD_VALUE = "@OLD_VALUE";
        private string PRIMARY_KEY = "@PRIMARY_KEY";
        private string SQL_CHECK_AUDIT_DATA_ID_UNIQUE = " SELECT COUNT(1) FROM @_@AUDIT_DATA WHERE ROWID = @ROWID ";
        private string SQL_DELETE_AUDIT_DATA = " DELETE FROM @_@AUDIT_DATA WHERE ROWID = @ROWID ";
        private string SQL_INSERT_AUDIT_DATA = " INSERT INTO @_@AUDIT_DATA ( TABLE_NAME, COL_NAME, CREATED_BY, CREATED_DATE, PRIMARY_KEY, ACTION, OLD_VALUE, NEW_VALUE) VALUES ( @TABLE_NAME, @COL_NAME, @CREATED_BY, GETDATE(), @PRIMARY_KEY, @ACTION, @OLD_VALUE, @NEW_VALUE)  ";
        private string SQL_SELECT_ALL_AUDIT_DATA = " SELECT  ROWID, TABLE_NAME, COL_NAME, CREATED_BY, CREATED_DATE, PRIMARY_KEY, ACTION, OLD_VALUE, NEW_VALUE  FROM  @_@AUDIT_DATA ";
        private string SQL_SELECT_ALL_AUDIT_DATA_BY_QUERY = "SELECT  ADA.ROWID, ADA.TABLE_NAME, ADA.COL_NAME, ADA.CREATED_BY, ADA.CREATED_DATE, ADA.PRIMARY_KEY, ADA.ACTION, ADA.OLD_VALUE, ADA.NEW_VALUE,ASA.COL_TYPE FROM @_@AUDIT_DATA  ADA  INNER JOIN @_@AUDIT_SCHEMA ASA  ON ADA.TABLE_NAME = ASA.TABLE_NAME AND ADA.COL_NAME = ASA.COL_NAME ";
        private string SQL_UPDATE_AUDIT_DATA = " UPDATE @_@AUDIT_DATA SET TABLE_NAME = @TABLE_NAME, COL_NAME = @COL_NAME, PRIMARY_KEY = @PRIMARY_KEY, ACTION = @ACTION, OLD_VALUE = @OLD_VALUE, NEW_VALUE = @NEW_VALUE WHERE ROWID = @ROWID  ";
        private string TABLE_NAME = "@TABLE_NAME";

        public bool CheckAuditDataIDUnique(string auditDataID, string whLoginID)
        {
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@ROWID", auditDataID) };
            return (DBHelper.ExecuteScalar(CommandType.Text, this.SQL_CHECK_AUDIT_DATA_ID_UNIQUE.Replace("@_@", whLoginID), paras).ToString() == "1");
        }

        public bool CheckAuditDataIDUnique(DataBase dataBase, DbTransaction tran, string auditDataID, string whLoginID)
        {
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@ROWID", auditDataID) };
            return (dataBase.ExecuteScalar(tran, CommandType.Text, this.SQL_CHECK_AUDIT_DATA_ID_UNIQUE.Replace("@_@", whLoginID), paras).ToString() == "1");
        }

        public int DeleteAuditData(List<string> auditDataID, string whLoginID)
        {
            int result = 0;
            DataBase dataBase = new DataBase();
            DbConnection conn = dataBase.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                for (int j = 0; j < auditDataID.Count; j++)
                {
                    SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@ROWID", auditDataID[j]) };
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_DELETE_AUDIT_DATA.Replace("@_@", whLoginID), paras);
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                conn.Close();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public int DeleteAuditData(DataBase dataBase, DbTransaction tran, List<string> auditDataID, string whLoginID)
        {
            int result = 0;
            try
            {
                for (int j = 0; j < auditDataID.Count; j++)
                {
                    SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@ROWID", auditDataID[j]) };
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_DELETE_AUDIT_DATA.Replace("@_@", whLoginID), paras);
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public DataSet GetAllAuditData(string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_AUDIT_DATA.Replace("@_@", whLoginID);
            return DBHelper.ExecuteDataSet(CommandType.Text, sql);
        }

        public DataSet GetAllAuditData(DataBase dataBase, DbTransaction tran, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_AUDIT_DATA.Replace("@_@", whLoginID);
            return dataBase.ExecuteDataSet(tran, CommandType.Text, sql);
        }

        public AuditDataInfo GetAuditDataByID(string auditdataID, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_AUDIT_DATA.Replace("@_@", whLoginID) + " WHERE ROWID = @ROWID  ";
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@ROWID", auditdataID) };
            AuditDataInfo auditDataInfo = null;
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, sql, paras))
            {
                if (reader.Read())
                {
                    auditDataInfo = new AuditDataInfo((reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["TABLE_NAME"].ToString(), reader["COL_NAME"].ToString(), reader["CREATED_BY"].ToString(), (reader["CREATED_DATE"].ToString() != "") ? DateTime.Parse(reader["CREATED_DATE"].ToString()) : new DateTime(), reader["PRIMARY_KEY"].ToString(), reader["ACTION"].ToString(), reader["OLD_VALUE"].ToString(), reader["NEW_VALUE"].ToString());
                }
            }
            return auditDataInfo;
        }

        public AuditDataInfo GetAuditDataByID(DataBase dataBase, DbTransaction tran, string auditdataID, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_AUDIT_DATA.Replace("@_@", whLoginID) + " WHERE ROWID = @ROWID  ";
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@ROWID", auditdataID) };
            AuditDataInfo auditDataInfo = null;
            IDataReader reader = dataBase.ExecuteReader(tran, CommandType.Text, sql, paras);
            if (reader.Read())
            {
                auditDataInfo = new AuditDataInfo((reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["TABLE_NAME"].ToString(), reader["COL_NAME"].ToString(), reader["CREATED_BY"].ToString(), (reader["CREATED_DATE"].ToString() != "") ? DateTime.Parse(reader["CREATED_DATE"].ToString()) : new DateTime(), reader["PRIMARY_KEY"].ToString(), reader["ACTION"].ToString(), reader["OLD_VALUE"].ToString(), reader["NEW_VALUE"].ToString());
            }
            if (!reader.IsClosed)
            {
                reader.Close();
            }
            return auditDataInfo;
        }

        public DataSet GetAuditDataByQueryList(List<string> sqlWhere, AuditDataQueryEntity auditdataQuery, string whLoginID)
        {
            string temp = this.SQL_SELECT_ALL_AUDIT_DATA_BY_QUERY.Replace("@_@", whLoginID);
            for (int i = 0; i < sqlWhere.Count; i++)
            {
                if (i == 0)
                {
                    temp = temp + " WHERE " + sqlWhere[i].ToString();
                }
                else
                {
                    temp = temp + " AND " + sqlWhere[i].ToString();
                }
            }
            if (!auditdataQuery.IsGetAll)
            {
                temp = PagingHelper.GetPagingSQL(temp, auditdataQuery.CurrentPage, auditdataQuery.PageSize, auditdataQuery.SortField, auditdataQuery.SortDirection);
            }
            return DBHelper.ExecuteDataSet(CommandType.Text, temp);
        }

        public DataSet GetAuditDataByQueryList(DataBase dataBase, DbTransaction tran, List<string> sqlWhere, AuditDataQueryEntity auditdataQuery, string whLoginID)
        {
            string temp = this.SQL_SELECT_ALL_AUDIT_DATA.Replace("@_@", whLoginID);
            for (int i = 0; i < sqlWhere.Count; i++)
            {
                if (i == 0)
                {
                    temp = temp + " WHERE " + sqlWhere[i].ToString();
                }
                else
                {
                    temp = temp + " AND " + sqlWhere[i].ToString();
                }
            }
            temp = PagingHelper.GetPagingSQL(temp, auditdataQuery.CurrentPage, auditdataQuery.PageSize, auditdataQuery.SortField, auditdataQuery.SortDirection);
            return dataBase.ExecuteDataSet(tran, CommandType.Text, temp);
        }

        public int InsertAuditData(AuditDataInfo auditDataInfo, string whLoginID)
        {
            int result = 0;
            DataBase db = new DataBase();
            DbConnection conn = db.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                SqlParameter[] paras = this.Set_AuditData_Parameters(auditDataInfo);
                if (paras != null)
                {
                    result += db.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_AUDIT_DATA.Replace("@_@", whLoginID), paras);
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                conn.Close();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public int InsertAuditData(DataBase dataBase, DbTransaction tran, AuditDataInfo auditDataInfo, string whLoginID)
        {
            int result = 0;
            try
            {
                SqlParameter[] paras = this.Set_AuditData_Parameters(auditDataInfo);
                if (paras != null)
                {
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_AUDIT_DATA.Replace("@_@", whLoginID), paras);
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        private SqlParameter[] Set_AuditData_Parameters(AuditDataInfo auditDataInfo)
        {
            SqlParameter[] paramArray = new SqlParameter[] { new SqlParameter(this.TABLE_NAME, SqlDbType.VarChar, 50), new SqlParameter(this.COL_NAME, SqlDbType.VarChar, 50), new SqlParameter(this.CREATED_BY, SqlDbType.VarChar, 20), new SqlParameter(this.PRIMARY_KEY, SqlDbType.VarChar, 0xff), new SqlParameter(this.ACTION, SqlDbType.VarChar, 15), new SqlParameter(this.OLD_VALUE, SqlDbType.VarChar, 0xff), new SqlParameter(this.NEW_VALUE, SqlDbType.VarChar, 0xff) };
            paramArray[0].Value = auditDataInfo.TableName;
            paramArray[1].Value = auditDataInfo.ColName;
            paramArray[2].Value = auditDataInfo.CreatedBy;
            if (!string.IsNullOrEmpty(auditDataInfo.PrimaryKey))
            {
                paramArray[3].Value = auditDataInfo.PrimaryKey;
            }
            else
            {
                paramArray[3].Value = DBNull.Value;
            }
            if (!string.IsNullOrEmpty(auditDataInfo.Action))
            {
                paramArray[4].Value = auditDataInfo.Action;
            }
            else
            {
                paramArray[4].Value = DBNull.Value;
            }
            if (!string.IsNullOrEmpty(auditDataInfo.OldValue))
            {
                paramArray[5].Value = auditDataInfo.OldValue;
            }
            else
            {
                paramArray[5].Value = DBNull.Value;
            }
            if (!string.IsNullOrEmpty(auditDataInfo.NewValue))
            {
                paramArray[6].Value = auditDataInfo.NewValue;
                return paramArray;
            }
            paramArray[6].Value = DBNull.Value;
            return paramArray;
        }

        public int UpdateAuditData(AuditDataInfo auditDataInfo, string whLoginID)
        {
            int result = 0;
            DataBase db = new DataBase();
            DbConnection conn = db.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                SqlParameter[] paras = this.Set_AuditData_Parameters(auditDataInfo);
                if (paras != null)
                {
                    result += db.ExecuteNonQuery(tran, CommandType.Text, this.SQL_UPDATE_AUDIT_DATA.Replace("@_@", whLoginID), paras);
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                conn.Close();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public int UpdateAuditData(DataBase dataBase, DbTransaction tran, AuditDataInfo auditDataInfo, string whLoginID)
        {
            int result = 0;
            try
            {
                SqlParameter[] paras = this.Set_AuditData_Parameters(auditDataInfo);
                if (paras != null)
                {
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_UPDATE_AUDIT_DATA.Replace("@_@", whLoginID), paras);
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }
    }
}

